package com.ly.spring.mvc.web;


import com.ly.spring.mvc.entity.Result;
import com.ly.spring.mvc.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;

//Controller       默认当前对象所有方法返回的是视图名
//RestController   默认。。。。。是json数据

@Controller
public class IndexController {

    @GetMapping("toTest")
    public String toTest(String name, HttpServletRequest request){
        System.out.println("toTest");
        request.setAttribute("myname", name);
        User user = new User();
        user.setName(name);
        request.getSession().setAttribute("myinfo", user);
        return "test.jsp";
    }


    @GetMapping("myinfo")
    @ResponseBody
    public User myinfo(@SessionAttribute User myinfo){
        return myinfo;
    }

    @RequestMapping("reg")
    @ResponseBody
    public Result reg(@Valid User user, Errors errors){
        if (errors.hasErrors()) {
            return new Result(0,"验证错误！",
                   errors.getAllErrors());
        }else {
            int i= 1/0;
            return new Result(1,"注册成功！",
                    null);
        }
    }

    @PostMapping("upload")
    @ResponseBody
    public Result uploadHead(@RequestParam("head") MultipartFile file,User user) throws IOException {
        String filename = file.getOriginalFilename();
        file.transferTo(new File("C:\\Users\\LY\\Desktop\\三期课堂视频\\2024年11月16日\\" + filename));

        return new Result(1,"文件上传成功",user);
    }
}
